﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static IPEndPoint iep;
        public static Socket sever, client;
        Thread a;
        
        private void Form1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            a = new Thread(ketnoi);
            a.Start();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] data = Encoding.Unicode.GetBytes(txtNhap.Text);
            client.Send(data,data.Length,SocketFlags.None);
            txtHienThi.Text += "\n" + txtNhap.Text;
            txtNhap.Text = "";
        }

      
       void ketnoi()
       {
           iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100);
           sever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           sever.Bind(iep);
           sever.Listen(10);
           txtHienThi.Text = "Đang kết nối";
           client = sever.Accept();
           txtHienThi.Text = "Chấp nhận kết nối từ" + client.RemoteEndPoint.ToString()
              + "\n Bạn có thể bắt đầu chat";
           while (true)
            {
                byte[] nhan = new byte[1024];
                client.Receive(nhan);
                txtHienThi.Text +="\n"+ Encoding.Unicode.GetString(nhan);
            }
       }

       
      
    }
}
